import {
  formatDate,
  formatDate2,
  formatDuration
} from '../../utils/date'
const app = getApp()
const domain = app.globalData.domain
// pages/warningReport/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    data: {},
    rules: [{}],
    templateOptions: [],
    templateVis: false,
    templateValue: null,
    termTypeValue: null,
    termTypeVis: false,
    termTypeOptions: [{
      label: '等于',
      value: 'eq'
    }, {
      label: '大于',
      value: 'gt'
    }, {
      label: '小于',
      value: 'lt'
    }, {
      label: '大于等于',
      value: 'gte'
    }, {
      label: '小于等于',
      value: 'lte'
    }]
  },
  onBack() {
    wx.navigateBack({
      delta: 1 // 这里的delta表示返回的页面数，如果 delta 大于现有页面数，则返回到首页
    });
  },
  addRule() {
    const rules = this.data.rules
    console.log('rules-before', rules)
    rules.push({})
    this.setData({
      rules
    })
  },
  showPicker(e) {
    console.log('e', e)
    this.setData({
      termTypeVis: true,
      opInfo: e.currentTarget.dataset
    });
  },
  addTerm(e) {
    console.log('onTermTypeChange', e)

    const {
      ruleindex,
      objectindex,
    } = e.currentTarget.dataset

    const rules = this.data.rules
    console.log('rules-before', rules, rules[ruleindex])
    if (!rules[ruleindex].whenExpr[objectindex].terms) {
      rules[ruleindex].whenExpr[objectindex].terms = []
    }
    rules[ruleindex].whenExpr[objectindex].terms.push({
      termType: 'eq',
      kind: 'reg_value'
    })
    console.log('rules', rules)
    this.setData({
      rules,
    })
  },
  onTermTypeChange(e) {
    console.log('onTermTypeChange', e)

    const {
      ruleindex,
      objectindex,
      termindex,
      type
    } = this.data.opInfo
    if (type === 'object-termType') {
      const rules = this.data.rules
      console.log('rules-before', rules, rules[ruleindex])
      rules[ruleindex].whenExpr[objectindex].termType = e.detail?.value?.[0]
      console.log('rules', rules)
      this.setData({
        rules,
      })
    }

    if (type === 'term-termType') {
      const rules = this.data.rules
      console.log('rules-before', rules, rules[ruleindex])
      rules[ruleindex].whenExpr[objectindex].terms[termindex].termType = e.detail?.value?.[0]
      console.log('rules', rules)
      this.setData({
        rules,
      })
    }
  },
  changeTermValue(e) {
    console.log(e)
    const value = e.detail.value
    console.log(e)
    const rules = this.data.rules;
    const {
      ruleindex,
      termindex,
      objectindex
    } = e.currentTarget.dataset
    console.log('rules[ruleindex].whenExpr[objectindex].terms[termindex]', rules[ruleindex].whenExpr[objectindex], termindex)
    if (!rules[ruleindex].whenExpr[objectindex].terms[termindex].value) rules[ruleindex].whenExpr[objectindex].terms[termindex].value = {}
    rules[ruleindex].whenExpr[objectindex].terms[termindex].value.value = value
    console.log('data', rules, value)
    this.setData({
      rules
    })
  },
  changeObjectValue(e) {
    console.log(e)
    const value = e.detail.value
    console.log(e)
    const rules = this.data.rules;
    const {
      ruleindex,
      objectindex
    } = e.currentTarget.dataset
    if (!rules[ruleindex].whenExpr[objectindex].value) rules[ruleindex].whenExpr[objectindex].value = {}
    rules[ruleindex].whenExpr[objectindex].value.value = value
    console.log('data', rules, value)
    this.setData({
      rules
    })
  },
  changeRuleValue(e) {
    const value = e.detail.value
    const rules = this.data.rules;
    const {
      target,
      index,
      type
    } = e.currentTarget.dataset
    console.log('e.currentTarget.dataset', e.currentTarget.dataset)
    if (type === 'ruleValue') {
      if (!rules[index].thenExpr) rules[index].thenExpr = [{}]
      if (!rules[index].thenExpr[0].value) rules[index].thenExpr[0].value = {}
      console.log('rules[index].thenExpr[0].value', rules[index].thenExpr[0].value)
      rules[index].thenExpr[0].value.value = value
    } else {
      rules[index][target] = value
    }
    console.log('data', rules, target, value)
    this.setData({
      rules
    })
  },
  changeValue(e) {
    console.log(e)
    const value = e.detail.value
    console.log(e)
    const data = this.data.data;
    const {
      target
    } = e.currentTarget.dataset
    data[target] = value
    console.log('data', data, target, value)
    this.setData({
      data
    })
  },
  init(id) {
    wx.request({
      url: `${domain}/admin-api/smc/plc-plan/get?id=${id}`,
      data: {},
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }
        // console.log('res', res)
        // let data = res?.data?.data?.list

        // data = data.map(item => {
        //   item.createTime = formatDate(item.createTime)
        //   return item
        // })
        console.log('res?.data?.rules', res?.data)
        this.setData({
          rules: res?.data?.data?.rules,
          data: res?.data?.data
        })
      }
    })
  },
  addData(newItem) {
    data.push(newItem);
    console.log("Added:", newItem);
  },
  deleteData(index) {
    if (index >= 0 && index < data.length) {
      data.splice(index, 1);
      console.log("Deleted item at index:", index);
    } else {
      console.log("Invalid index:", index);
    }
  },
  updateData(index, updatedFields) {
    if (index >= 0 && index < data.length) {
      const item = data[index];
      Object.assign(item, updatedFields);
      console.log("Updated item at index:", index);
    } else {
      console.log("Invalid index:", index);
    }
  },
  transformData(data) {
    return data.map(item => {
      const transformedItem = {
        item,
        label: item.name,
        value: item.id,
        children: item.confNodes?.length > 0 ? this.transformData(item.confNodes) : null
      };
      return transformedItem;
    });
  },
  showCascader(e) {
    console.log('e', e)
    this.setData({
      templateVis: true,
      opInfo: e.currentTarget.dataset
    });
  },
  onTemplateChange(e) {
    console.log(e);
    this.setData({
      templateValue: e.detail.value
    })
  },
  onTemplateClose(e) {
    console.log('onclose', e, this.data.templateValue)
    this.setData({
      templateVis: false
    })
    if (e.detail.trigger !== 'finish') {
      this.setData({
        templateValue: null,
      })
      return
    }

    const item = this.findItemByCode(this.data.templateOptions, this.data.templateValue)
    console.log('item', item)
    if (item?.type !== "metric") {
      wx.showToast({
        title: '选择项类型不匹配，请重新选择',
        icon: 'none'
      })
      return
    }

    const {
      ruleindex,
      objectindex,
      termindex,
      type
    } = this.data.opInfo
    if (type === 'rule-confNodeId') {
      const rules = this.data.rules
      console.log('rules-before', rules, rules[ruleindex])
      if (!rules[ruleindex].thenExpr) rules[ruleindex].thenExpr = [{}]
      rules[ruleindex].thenExpr[0].confNodeId = this.data.templateValue
      console.log('rules', rules)
      this.setData({
        rules,
        templateValue: null
      })
    }

    if (type === 'object-confNodeId') {
      const rules = this.data.rules
      console.log('rules-before', rules)
      rules[ruleindex].whenExpr[objectindex].confNodeId = this.data.templateValue
      console.log('rules', rules)
      this.setData({
        rules,
        templateValue: null
      })
    }

    if (type === 'term-confNodeId') {
      const rules = this.data.rules
      console.log('rules-before', rules)
      rules[ruleindex].whenExpr[objectindex].terms[termindex].confNodeId = this.data.templateValue
      console.log('rules', rules)
      this.setData({
        rules,
        templateValue: null
      })
    }

  },
  generateCodeToNameMap(data) {
    const result = {};

    function traverse(nodes, parentName = "") {
      nodes.forEach(node => {
        const currentName = parentName ? `${parentName}/${node.name}` : node.name;
        result[node.id] = currentName;

        if (node.confNodes && node.confNodes.length > 0) {
          traverse(node.confNodes, currentName);
        }
      });
    }

    // 假设 data 是你提供的 JSON 数据中的 confNodes 部分
    traverse(data);

    return result;
  },
  initTemplate(id) {
    console.log('id', id)
    wx.request({
      url: `${domain}/admin-api/smc/scene-conf/get?id=${id}`,
      data: {},
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }

        const templateOptions = this.transformData(res?.data?.data?.confNodes || [])
        const merNameMap = this.generateCodeToNameMap(res?.data?.data?.confNodes || [])
        console.log('merNameMap', merNameMap)
        console.log('res?.data', res?.data?.data?.confNodes, templateOptions)
        this.setData({
          merNameMap,
          templateOptions
        })
      }
    })
  },
  findItemByCode(data, id) {
    // 遍历当前层级的数据
    for (const item of data) {
      if (item.item.id === id) {
        return item.item; // 如果找到匹配的 code，返回对应的 item
      }

      // 如果当前 item 有子节点，递归查找
      if (item.children && item.children.length > 0) {
        const result = this.findItemByCode(item.children, id);
        if (result) return result; // 如果在子节点中找到，返回结果
      }
    }

    return null; // 如果未找到，返回 null
  },
  addwhenExpr(e) {
    const {
      ruleindex
    } = e.currentTarget.dataset
    const rules = this.data.rules

    wx.showModal({
      title: '提示',
      content: '请选择添加类型',
      cancelText: '普通类型',
      confirmText: '聚合类型',
      complete: (res) => {
        if (!rules[ruleindex].whenExpr) rules[ruleindex].whenExpr = []
        if (res.cancel) {
          rules[ruleindex].whenExpr.push({
            termType: 'eq',
            value: {}
          })
          this.setData({
            rules
          })
        }

        if (res.confirm) {
          rules[ruleindex].whenExpr.push({
            aggType: 'sum',
            termType: 'eq',
            value: {}
          })
          this.setData({
            rules
          })
        }
      }
    })


  },
  deleteTerm(e) {
    const {
      objectindex,
      ruleindex,
      termindex
    } = e.currentTarget.dataset
    const rules = this.data.rules
    rules[ruleindex].whenExpr[objectindex].terms.splice(termindex, 1)
    this.setData({
      rules
    })
  },
  deletewhenExpr(e) {
    const {
      objectindex,
      ruleindex
    } = e.currentTarget.dataset
    const rules = this.data.rules
    rules[ruleindex].whenExpr.splice(objectindex, 1)
    this.setData({
      rules
    })
  },
  deleteRule(e) {
    const {
      ruleindex
    } = e.currentTarget.dataset
    const rules = this.data.rules
    rules.splice(ruleindex, 1)
    this.setData({
      rules
    })
  },
  save() {
    if (!this.data.options.id) {
      this.create()
      return
    }
    wx.request({
      url: `${domain}/admin-api/smc/plc-plan/update`,
      method: 'PUT',
      data: {
        ...this.data.data,
        sceneId: this.data.options.sceneId,
        confId: this.data.options.confId,
        rules: this.data.rules
      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }

        if (res?.data?.code !== 0) {
          wx.showToast({
            title: res.data?.msg,
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: '保存成功',
            icon: 'none'
          })
          wx.navigateBack({
            delta: 1
          })
        }
      }
    })
  },
  create() {
    wx.request({
      url: `${domain}/admin-api/smc/plc-plan/create`,
      method: 'POST',
      data: {
        ...this.data.data,
        sceneId: this.data.options.sceneId,
        confId: this.data.options.confId,
        rules: this.data.rules
      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }

        if (res?.data?.code !== 0) {
          wx.showToast({
            title: res.data?.msg,
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: '保存成功',
            icon: 'none'
          })
          wx.navigateBack({
            delta: 1
          })
        }
      }
    })
  },

  onLoad(options) {
    this.setData({
      options
    })

    if (options.id)
      this.init(options.id)

    if (options.confId)
      // this.initTemplate('41')
      this.initTemplate(options.confId)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})